﻿using UnityEngine;
using System.Collections;

public class RoadSpawn : MonoBehaviour
{
		public GameObject[] roads;
		private GameObject current_road;
		private GameObject	next_road;

		void Start ()
		{
				// Start calling the Spawn function repeatedly after a delay .
				//	InvokeRepeating ("Spawn", 1, 1);
				int index = Random.Range (0, roads.Length);
				current_road = (GameObject)Instantiate (roads [index], new Vector3 (0, 0, 0), transform.rotation);
				index = Random.Range (0, roads.Length);	
				next_road = (GameObject)Instantiate (roads [index], new Vector3 (current_road.collider2D.bounds.size.x + 2, 0, 0), transform.rotation);
		}
		void Update ()
		{
				if (Vector3.Distance (current_road.transform.position, transform.position) > current_road.collider2D.bounds.size.x) {
						GameObject.Destroy (current_road);
						createNewRoad ();
				}

		}

		void createNewRoad ()
		{
				current_road = next_road;
				int index = Random.Range (0, roads.Length);
				next_road = (GameObject)Instantiate (roads [index], new Vector3 (current_road.collider2D.bounds.size.x + 1, 0, 0), transform.rotation);
		}


}
